Laravel
Models Migration Relation
Introduction,istallation Strucutre,model,migration Migration,Models,Relation
Les Relations
BelongsTo HasOne HasMany BelongsToMany HasManyThrough
Exemples des Relations
Relations:oneToMany,ManyToMany... Relations:Exemples
Exercices
Exercice 1 Exercice 2
Controllers Views Routes
Routes,Controller,Model,view CRUD: Etudiant CRUD: Car CRUD,Recherche: Book
Validation
Exemple :Projets
Api:Laravel +React
Middleware

Seeders & Factories

Authenfication
Layouts





La relation "BelongsToMany" dans Laravel

La relation "BelongsToMany" est utilisée lorsque deux modèles sont liés par une relation de plusieurs à plusieurs à l'aide d'une table pivot intermédiaire. Dans cette relation, chaque enregistrement du premier modèle peut être associé à plusieurs enregistrements du deuxième modèle, et vice versa.
Exemple 1
un exemple de la relation "BelongsToMany" dans le contexte d'une application de gestion d'étudiants et de cours, où chaque étudiant peut être inscrit à plusieurs cours et chaque cours peut avoir plusieurs étudiants inscrits. Les tables associées seront students, courses, et une table pivot course_student. Migration pour la table students :
/ database/migrations/YYYY_MM_DD_create_students_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id('idStudent'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->string('email')->unique();
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('students');
    }
}
Migration pour la table courses :
/ database/migrations/YYYY_MM_DD_create_courses_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('courses', function (Blueprint $table) {
            $table->id('idCourse'); // Nommer la clé primaire avec idTable
            $table->string('title');
            $table->string('description');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('courses');
    }
}
Migration pour la table pivot course_student :
/ database/migrations/YYYY_MM_DD_create_course_student_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('course_student', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('course_id');
            $table->unsignedBigInteger('student_id');
            
            $table->foreign('course_id')->references('idCourse')->on('courses');
            $table->foreign('student_id')->references('idStudent')->on('students');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('course_student');
    }
}
Modèle pour la table Student :
/ app/Models/Student.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $table = 'students';
    protected $primaryKey = 'idStudent'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'email'];

    public function courses()
    {
        return $this->belongsToMany(Course::class, 'course_student', 'student_id', 'course_id');
    }
}
Modèle pour la table Course :
/ app/Models/Course.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    protected $table = 'courses';
    protected $primaryKey = 'idCourse'; // Nommer la clé primaire avec idTable
    protected $fillable = ['title', 'description'];

    public function students()
    {
        return $this->belongsToMany(Student::class, 'course_student', 'course_id', 'student_id');
    }
}
Dans cet exemple, chaque étudiant (Student) peut être inscrit à plusieurs cours (Course), et chaque cours peut avoir plusieurs étudiants inscrits. La méthode belongsToMany dans les modèles Student et Course définit la relation "BelongsToMany" en spécifiant le modèle cible, le nom de la table pivot (course_student), et les clés étrangères associées. Vous pouvez ensuite accéder aux cours auxquels un étudiant est inscrit ou aux étudiants inscrits à un cours de la manière suivante :
Exemple 2
un autre exemple de la relation "BelongsToMany" dans le contexte d'une application de réseau social, où les utilisateurs peuvent appartenir à plusieurs groupes et chaque groupe peut avoir plusieurs utilisateurs. Les tables associées seront users, groups, et une table pivot user_group.
Migration pour la table users :
/ database/migrations/YYYY_MM_DD_create_users_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id('id'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}
Migration pour la table groups :
/ database/migrations/YYYY_MM_DD_create_groups_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->id('idGroup'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->text('description');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('groups');
    }
}
Migration pour la table pivot user_group :
/ database/migrations/YYYY_MM_DD_create_user_group_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('user_group', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('group_id');
            
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('group_id')->references('idGroup')->on('groups');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('user_group');
    }
}
Modèle pour la table User :
/ app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'email', 'password'];

    public function groups()
    {
        return $this->belongsToMany(Group::class, 'user_group', 'user_id', 'group_id');
    }
}
Modèle pour la table Group :
/ app/Models/Group.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $table = 'groups';
    protected $primaryKey = 'idGroup'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'description'];

    public function users()
    {
        return $this->belongsToMany(User::class, 'user_group', 'group_id', 'user_id');
    }
}
Dans cet exemple, chaque utilisateur (User) peut appartenir à plusieurs groupes (Group), et chaque groupe peut avoir plusieurs utilisateurs. La méthode belongsToMany dans les modèles User et Group définit la relation "BelongsToMany" en spécifiant le modèle cible, le nom de la table pivot (user_group), et les clés étrangères associées. Vous pouvez ensuite accéder aux groupes auxquels un utilisateur appartient ou aux utilisateurs appartenant à un groupe de la manière suivante :
Exemple 3
un autre exemple de la relation "BelongsToMany" dans le contexte d'une application de vente en ligne, où chaque produit peut appartenir à plusieurs catégories et chaque catégorie peut avoir plusieurs produits. Les tables associées seront products, categories, et une table pivot category_product.
Migration pour la table products :
/ database/migrations/YYYY_MM_DD_create_products_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id('idProduct'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->text('description');
            $table->decimal('price', 8, 2);
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}
Migration pour la table categories :
/ database/migrations/YYYY_MM_DD_create_categories_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id('idCategory'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->text('description');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('categories');
    }
}
Migration pour la table pivot category_product :
/ database/migrations/YYYY_MM_DD_create_category_product_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('product_id');
            
            $table->foreign('category_id')->references('idCategory')->on('categories');
            $table->foreign('product_id')->references('idProduct')->on('products');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('category_product');
    }
}
Modèle pour la table Product :
/ app/Models/Product.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'idProduct'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'description', 'price'];

    public function categories()
    {
        return $this->belongsToMany(Category::class, 'category_product', 'product_id', 'category_id');
    }
}
Modèle pour la table Category :
/ app/Models/Category.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
    protected $primaryKey = 'idCategory'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'description'];

    public function products()
    {
        return $this->belongsToMany(Product::class, 'category_product', 'category_id', 'product_id');
    }
}
Dans cet exemple, chaque produit (Product) peut appartenir à plusieurs catégories (Category), et chaque catégorie peut avoir plusieurs produits. La méthode belongsToMany dans les modèles Product et Category définit la relation "BelongsToMany" en spécifiant le modèle cible, le nom de la table pivot (category_product), et les clés étrangères associées.